package com.yangmf.auto_message_handle.task;

import com.mikuac.shiro.core.Bot;
import com.mikuac.shiro.core.BotContainer;
import com.mikuac.shiro.dto.action.common.ActionData;
import com.mikuac.shiro.dto.action.response.GroupAtAllRemainResp;
import com.yangmf.auto_message_handle.constant.Message_Type;
import com.yangmf.auto_message_handle.pojo.entity.DataBlocking;
import com.yangmf.auto_message_handle.pojo.entity.DataManager;
import com.yangmf.auto_message_handle.pojo.entity.Event;
import com.yangmf.auto_message_handle.pojo.entity.Imageurl;
import com.yangmf.auto_message_handle.service.EventService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class Event_Handle_Task {

    @Autowired
    private EventService eventService;

    @Autowired
    private DataManager dataManager;

    @Autowired
    private DataBlocking dataBlocking;

    @Resource
    private BotContainer botContainer;




    /**
     * 每10分钟执行一次
     */
    @Scheduled(cron =  "0 0/5 * * * ?")
    public void handleEvent() {
        log.info("开始处理事件");
        synchronized (dataManager) {
            if (dataManager.getDataMap().size() > 0) {
                ConcurrentHashMap<String, Event> copy_data= new ConcurrentHashMap<>(dataManager.getDataMap());
                for (String key : copy_data.keySet())
                {
                    LocalDateTime now = LocalDateTime.now();
                    LocalDateTime start_time =copy_data.get(key).getStartTime();
                    Duration duration = Duration.between(start_time, now);
                    /**
                     * 10分钟内的事件不做处理
                     */
                    if(duration.toMinutes()<3)
                        continue;
                    else{
                        eventService.addEvent(copy_data.get(key));
                        dataManager.removeData(key);
                        log.info("添加事件{}成功",key);

                    }




                }

            }


        }
        log.info("处理事件完成");
    }


    @Scheduled(cron = "0 0/3 * * * ?")
    public void handleImage() throws IOException {
        log.info("开始处理阻塞图片");
        BlockingQueue<Imageurl> queue = dataBlocking.getData();
        Imageurl imageurl;

        // 只处理当前队列中的元素，不处理新添加的
        int initialSize = queue.size();
        for (int i = 0; i < initialSize; i++) {
            imageurl = queue.poll();
            if (imageurl == null) break;

            LocalDateTime now = LocalDateTime.now();
            LocalDateTime create_time = imageurl.getCreate_time();
            Duration duration = Duration.between(create_time, now);

            if (duration.toMinutes() > 1) {
                String nearestEventKey = findNearestEventKey(imageurl.getCreate_time());
                if (nearestEventKey != null) {
                    log.info("图片处理成功，添加到事件{}中", nearestEventKey);
                    dataManager.addData(nearestEventKey, imageurl.getUrl(), Message_Type.IMAGE_MESSAGE,imageurl.getId());
                } else {
                    // 超过最大重试次数则丢弃
                    if (imageurl.getRetryCount() < 3) {
                        imageurl.setRetryCount(imageurl.getRetryCount() + 1);
                        imageurl.setCreate_time(now);
                        queue.offer(imageurl);
                    } else {
                        log.warn("图片处理失败，已达到最大重试次数: {}", imageurl);
                    }
                }
            } else {
                // 未过期，重新放回队列
                queue.offer(imageurl);
            }
        }
        log.info("处理阻塞图片完成");
    }


    private String findNearestEventKey(LocalDateTime targetTime) {
        String nearestEventKey = null;
        Duration nearestDuration = Duration.ofDays(100000); // 初始化为一个很大的持续时间

        for (String key : dataManager.getKeys()) {
            Event event = dataManager.getDataMap().get(key);
            LocalDateTime startTime = event.getStartTime();
            Duration duration = Duration.between(startTime, targetTime);

            // 取绝对值比较时间差
            if (Math.abs(duration.toMinutes()) < nearestDuration.toMinutes()) {
                nearestDuration = duration;
                nearestEventKey = key;
            }
        }

        return nearestEventKey;
    }
@Scheduled(cron = "0 40 21 * * ?")

    public void sendMessage()
{
    long botId = 3621293964L;
    // 通过机器人账号取出 Bot 对象
    Bot bot = botContainer.robots.get(botId);

    bot.sendGroupMsg(715863532, "同学们记得打卡哦！", true);

    ActionData<GroupAtAllRemainResp> groupAtAllRemain = bot.getGroupAtAllRemain(715863532);
    Integer remainAtAllCountForGroup = groupAtAllRemain.getData().getRemainAtAllCountForGroup();

    if (remainAtAllCountForGroup > 0) {
        bot.sendGroupMsg(715863532, "[CQ:at,qq=all] ", false);


    }


}

}
